<template>
  <el-dialog v-model="knowledgeBaseDialogVisible" title="从知识库中选择" width="70%" :close-on-click-modal="false" class="knowledge-base-dialog">
    <div class="knowledge-search-container">
      <el-input v-model="knowledgeSearchKeyword" placeholder="输入关键词搜索知识库内容" prefix-icon="Search" clearable @input="searchKnowledgeBase">
        <template #append>
          <el-button @click="searchKnowledgeBase">搜索</el-button>
        </template>
      </el-input>
    </div>

    <div class="knowledge-result-container">
      <div v-if="knowledgeLoading" class="knowledge-loading">
        <el-skeleton :rows="6" animated />
      </div>

      <el-empty v-else-if="knowledgeResults.length === 0" description="没有找到相关知识内容" />

      <div v-else class="knowledge-results">
        <div
          v-for="item in knowledgeResults"
          :key="item.id"
          class="knowledge-item"
          :class="{ 'selected': selectedKnowledgeIds.includes(item.id) }"
          @click="toggleKnowledgeSelection(item)"
        >
          <div class="knowledge-item-header">
            <div class="knowledge-item-title">{{ item.title }}</div>
            <el-tag size="small" :type="getTagTypeByCategory(item.category)">{{ item.category }}</el-tag>
          </div>

          <div class="knowledge-item-content">
            <p class="knowledge-item-summary">{{ item.summary }}</p>
            <div class="knowledge-item-match">
              <div class="match-title">匹配章节：</div>
              <div v-for="(match, index) in item.matchSections" :key="index" class="match-section">
                {{ match }}
              </div>
            </div>
          </div>

          <div class="knowledge-item-footer">
            <span class="knowledge-item-date">更新时间：{{ formatDate(item.updateTime) }}</span>
            <span class="knowledge-item-usage">使用次数：{{ item.usageCount }}</span>
          </div>

          <el-icon v-if="selectedKnowledgeIds.includes(item.id)" class="selection-icon"><Check /></el-icon>
        </div>
      </div>
    </div>

    <div class="knowledge-pagination">
      <el-pagination
        v-model:current-page="knowledgePage"
        v-model:page-size="knowledgePageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="knowledgeTotalCount"
        @size-change="searchKnowledgeBase"
        @current-change="searchKnowledgeBase"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selection-count" v-if="selectedKnowledgeIds.length > 0"> 已选择 {{ selectedKnowledgeIds.length }} 项 </span>
        <el-button @click="knowledgeBaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applySelectedKnowledge" :disabled="selectedKnowledgeIds.length === 0"> 应用所选内容 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// ... 现有代码 ...

// 知识库弹窗相关状态
const knowledgeBaseDialogVisible = ref(false);
const knowledgeSearchKeyword = ref('');
/*   const knowledgeCategory = ref('');
  const knowledgeSortOrder = ref('relevance'); */
const knowledgePage = ref(1);
const knowledgePageSize = ref(10);
const knowledgeTotalCount = ref(0);
const knowledgeLoading = ref(false);
const knowledgeResults = ref<any[]>([]);
const selectedKnowledgeIds = ref<string[]>([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
//用深度监听 消息
watch(
  () => props.visible,
  () => {
    knowledgeBaseDialogVisible.value = true;
    knowledgeSearchKeyword.value = '';
    selectedKnowledgeIds.value = [];
    searchKnowledgeBase();
  },
  { deep: true }
);
// 打开知识库选择弹窗
// const openKnowledgeBaseDialog = () => {};

// 搜索知识库
const searchKnowledgeBase = debounce(async () => {
  try {
    knowledgeLoading.value = true;

    // 这里替换为实际的API调用
   /*  const response = await apiService.searchKnowledgeBase({
      keyword: knowledgeSearchKeyword.value,
      category: knowledgeCategory.value,
      sortBy: knowledgeSortOrder.value,
      page: knowledgePage.value,
      pageSize: knowledgePageSize.value
    }); */
/* 
    knowledgeResults.value = response.data.items;
    knowledgeTotalCount.value = response.data.total; */
  } catch (error) {
    console.error('搜索知识库失败:', error);
    ElMessage.error('搜索知识库时发生错误');
  } finally {
    knowledgeLoading.value = false;
  }
}, 300);

// 根据类别获取标签类型
const getTagTypeByCategory = (category: string) => {
  const typeMap: Record<string, string> = {
    'tender': 'success',
    'technical': 'primary',
    'summary': 'warning',
    'standard': 'info'
  };
  return typeMap[category] || '';
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 切换知识项的选中状态
const toggleKnowledgeSelection = (item: any) => {
  const index = selectedKnowledgeIds.value.indexOf(item.id);
  if (index === -1) {
    selectedKnowledgeIds.value.push(item.id);
  } else {
    selectedKnowledgeIds.value.splice(index, 1);
  }
};

// 应用所选知识内容
const applySelectedKnowledge = async () => {
  try {
    // const selectedItems = knowledgeResults.value.filter((item) => selectedKnowledgeIds.value.includes(item.id));

    // 这里处理所选内容的应用逻辑
    // 例如：将所选内容添加到当前目录或章节内容中

    ElMessage.success('已成功应用所选知识内容');
    knowledgeBaseDialogVisible.value = false;
  } catch (error) {
    console.error('应用知识内容失败:', error);
    ElMessage.error('应用知识内容时发生错误');
  }
};

// 防抖函数实现
function debounce(fn: Function, delay: number) {
  let timer:any
  return function (...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}
</script>

<style scoped>
/* 知识库弹窗样式 */
.knowledge-base-dialog {
  --primary-color: #1890ff;
  --hover-color: #e6f7ff;
  --border-color: #ebeef5;
  --text-color: #303133;
  --light-text: #909399;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid var(--border-color);
  padding: 20px;
  margin: 0;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.knowledge-search-container {
  margin-bottom: 20px;
}

.knowledge-filter {
  display: flex;
  gap: 15px;
  margin-top: 15px;
}

.knowledge-result-container {
  min-height: 400px;
  max-height: 50vh;
  overflow-y: auto;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 10px;
  background-color: #f9fafc;
}

.knowledge-loading {
  padding: 20px;
}

.knowledge-results {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.knowledge-item {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid var(--border-color);
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.knowledge-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: var(--primary-color);
}

.knowledge-item.selected {
  background-color: var(--hover-color);
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.selection-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  color: var(--primary-color);
  font-size: 20px;
}

.knowledge-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.knowledge-item-title {
  font-weight: 600;
  font-size: 16px;
  color: var(--text-color);
}

.knowledge-item-content {
  margin-bottom: 15px;
}

.knowledge-item-summary {
  margin-bottom: 10px;
  color: var(--text-color);
  line-height: 1.6;
}

.knowledge-item-match {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-top: 10px;
}

.match-title {
  color: var(--light-text);
  font-size: 14px;
}

.match-section {
  background-color: #f0f9ff;
  color: var(--primary-color);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.knowledge-item-footer {
  display: flex;
  justify-content: space-between;
  color: var(--light-text);
  font-size: 13px;
}

.knowledge-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding: 10px 20px;
}

.selection-count {
  color: var(--primary-color);
  font-weight: 500;
}

/* 添加知识库按钮样式 */
.add-from-knowledge-base {
  margin-bottom: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background-color: #f5f7fa;
  border: 1px dashed #c0c4cc;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-from-knowledge-base:hover {
  background-color: #ecf5ff;
  border-color: var(--primary-color);
  color: var(--primary-color);
}
</style>
